<?php

namespace app\admin\controller\tongcheng;

use addons\tongcheng\enum\DeliveryRefundStatus;
use addons\tongcheng\enum\UserRole;
use addons\tongcheng\library\DeliveryService;
use addons\tongcheng\library\RefundService;
use addons\tongcheng\model\CouponRecordModel;
use app\admin\model\tongcheng\DeliveryOrderRefundModel;
use app\admin\model\tongcheng\DeliveryTransferModel;
use app\admin\model\tongcheng\UserAddressModel;
use app\common\controller\Backend;
use think\Env;

/**
 * 配送单
 *
 * @icon fa fa-circle-o
 */
class DeliveryOrder extends Backend
{
    protected $noNeedRight = ['detail', 'riderAssign', 'riderArrive', 'riderDelivering', 'complete', 'cancel', 'refundAccept', 'refundReject'];

    /**
     * DeliveryOrderModel模型对象
     * @var \app\admin\model\tongcheng\DeliveryOrderModel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\tongcheng\DeliveryOrderModel;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("cancelRoleList", $this->model->getCancelRoleList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user', 'zone', 'module', 'rider'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname']);
                $row->getRelation('zone')->visible(['name']);
                $row->getRelation('module')->visible(['name']);
                $row->getRelation('rider')->visible(['real_name']);
            }

            // $result = array("total" => $list->total(), "rows" => $list->items());

            $total = $list->total();
            $rows  = $list->items();

            if (Env::get('app.preview', false)) {
                foreach ($rows as &$row) {
                    $row['start_mobile'] = UserAddressModel::hideUserMobile($row['start_mobile'] ?? '');
                    $row['end_mobile']   = UserAddressModel::hideUserMobile($row['end_mobile'] ?? '');
                }
            }

            $result = array("total" => $total, "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 订单详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids, ['user', 'zone', 'module', 'rider', 'actions', 'fees']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (!empty($row['fees']) && !empty($row['fees']['coupon_record_id'])) {
            $row['coupon_record'] = CouponRecordModel::get($row['fees']['coupon_record_id']);
        }

        // dd($row->toArray());

        // 加载超时理赔信息
        DeliveryService::loadOvertimeClaimInfo($row, $row['fees']);

        if (Env::get('app.preview', false)) {
            $row['start_mobile'] = UserAddressModel::hideUserMobile($row['start_mobile']);
            $row['end_mobile']   = UserAddressModel::hideUserMobile($row['end_mobile']);
        }

        $this->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 指派骑手
     */
    public function riderAssign()
    {
        $order_id = input('order_id/d');
        $rider_id = input('rider_id/d');

        if (!$order_id) {
            $this->error('缺少订单ID参数');
        }
        if (!$rider_id) {
            $this->error('缺少骑手ID参数');
        }

        // 骑手在线检测


        // $row = $this->model->get($order_id);
        DeliveryService::riderReceive($order_id, $rider_id, UserRole::ADMIN, $this->auth->id);
        $this->success('操作成功');
    }

    /**
     * 到达取货点
     */
    public function riderArrive($ids = null)
    {
        // $row = $this->model->get($ids);
        DeliveryService::riderArrive($ids, 0, UserRole::ADMIN, $this->auth->id);
        $this->success('操作成功');
    }

    /**
     * 骑手开始配送
     */
    public function riderDelivering($ids = null)
    {
        $row = $this->model->get($ids);
        DeliveryService::riderDelivering($ids, $row->rider_id, UserRole::ADMIN, $this->auth->id);
        $this->success('操作成功');
    }

    /**
     * 完成配送
     */
    public function complete($ids = null)
    {
        $row = $this->model->get($ids);
        DeliveryService::complete($ids, $row->rider_id, $row['receive_code'] ?? '', UserRole::ADMIN, $this->auth->id);
        $this->success('操作成功');
    }

    /**
     * 订单取消
     */
    public function cancel($ids = null)
    {
        DeliveryService::cancel($ids, $this->auth->id, UserRole::ADMIN, '后台取消订单');
        $this->success('操作成功');
    }

    /**
     * 同意退款
     */
    public function refundAccept($ids = null)
    {
        $row    = $this->model->get($ids);
        $refund = DeliveryOrderRefundModel::where('order_id', $ids)->where('status', DeliveryRefundStatus::WAIT)->find();
        if (!$refund) {
            $this->error('没有可退款的申请');
        }

        RefundService::acceptDeliveryOrderRefund($row, $refund, $this->auth->id, UserRole::ADMIN);
        $this->success('操作成功');
    }

    /**
     * 拒绝退款
     */
    public function refundReject($ids = null)
    {
        $reject_remark = input('reject_remark/s');
        if (!$reject_remark) {
            $this->error('请填写拒绝退款理由');
        }

        $row    = $this->model->get($ids);
        $refund = DeliveryOrderRefundModel::where('order_id', $ids)->where('status', DeliveryRefundStatus::WAIT)->find();
        if (!$refund) {
            $this->error('没有可退款的申请');
        }
        RefundService::rejectDeliveryOrderRefund($row, $row->refund, $reject_remark, $this->auth->id, UserRole::ADMIN);
        $this->success('操作成功');
    }


    /**
     * 发起转单
     */
    public function transfer()
    {
        $order_id = input('order_id/d');
        $rider_id = input('rider_id/d');

        if (!$order_id) {
            $this->error('缺少订单ID参数');
        }
        if (!$rider_id) {
            $this->error('缺少骑手ID参数');
        }

        $row = $this->model->get($order_id);
        DeliveryTransferModel::add($row['zone_id'], $row['rider_id'], $order_id, $rider_id, UserRole::ADMIN, $this->auth->id);
        $this->success('操作成功');
    }
}
